var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var app = getApp()
var startPoint;

Page({
  data: {
    banner: [
      {'gphoto':"/static/images/address.png"},
      {'gphoto':"/static/images/close.gif"},
      {'gphoto':"/static/images/about_us.png"}
    ],
    barimg:['/static/images/cha.png',
            '/static/images/coffic.png',
            '/static/images/naicha.png',
            '/static/images/xiaochi.png',
            '/static/images/xiaotie.png',
            '/static/images/natie.png',
            '/static/images/shengye.png',
            '/static/images/jingdian.png',
            '/static/images/cha.png',
            
          ],
    // 记录属性
    attrribute: [],
    // 杯型
    cups: [
      { 'name': '大杯', 'stuate': true },
      { 'name': '中杯', 'stuate': false }
    ],
    // 冰毒
    ico: [
      { 'name': '少冰', 'stuate': true },
      { 'name': '去冰', 'stuate': false },
      { 'name': '常温', 'stuate': false },
      { 'name': '热饮', 'stuate': false },
    ],
    // 糖度
    sugar: [
      { 'name': '三分糖', 'stuate': true },
      { 'name': '五分糖', 'stuate': false },
      { 'name': '七分糖', 'stuate': false },
      { 'name': '全糖', 'stuate': false },
      { 'name': '不加糖', 'stuate': false },
    ],

    dosing: [
      { 'name': '珍珠', 'stuate': true },
      { 'name': '波霸', 'stuate': false },
      { 'name': '椰果', 'stuate': false },
      { 'name': '布丁', 'stuate': false },
      { 'name': '燕麦', 'stuate': false },
    ],
    cup: false,
    // 属性选择
    isdosing: false,
    // 取餐方式
    shopeat: 1,
    outeat: 0,
    // 店铺
    shop: {},
    // 弹出层
    show: false,

    // 购物车相关的
    //按钮位置参数
    // buttonTop: 458,
    // buttonLeft: 345,
    // windowHeight: '',
    // windowWidth: '',
    // //角标显示数字
    // corner_data:0,
    tabIndex: 0,
    id: 0,
    item: [],
    // 统计商品数量和价格
    orderCount: {
      num: 0,
      money: 0.00
    },
    bottomFlag: false,
    // 提交的订单
    orders: true,
    menus: [{
      id: 0,
      menu: '菜单1'
    }, {
      id: 1,
      menu: '菜单2'
    }, {
      id: 2,
      menu: '菜单3'
    }, {
      id: 3,
      menu: '菜单4'
    }, {
      id: 4,
      menu: '菜单5'
    }],
    // 商品列表
    items: [{
      id: 1,
      title: '黄金菇',
      price: 66,
      active: false,
      num: 1,
      image: 'image/1.jpg',
      menu_id: 0
    }, {
      id: 2,
      title: '小野鱼',
      price: 50,
      active: false,
      num: 1,
      image: 'image/2.jpg',
      menu_id: 0
    }, {
      id: 3,
      title: '手抓小排',
      price: 66,
      active: false,
      num: 1,
      image: 'image/3.jpg',
      menu_id: 0
    }, {
      id: 4,
      title: '珍珠蛋糕',
      price: 88,
      active: false,
      num: 1,
      image: 'image/4.jpg',
      menu_id: 1
    }, {
      id: 5,
      title: '水果蛋糕',
      price: 66,
      active: false,
      num: 1,
      image: 'image/5.jpg',
      menu_id: 1
    }, {
      id: 6,
      title: '卡通蛋糕',
      price: 79,
      active: false,
      num: 1,
      image: 'image/6.png',
      menu_id: 1
    }, {
      id: 7,
      title: '芝士年糕',
      price: 58,
      active: false,
      num: 1,
      image: 'image/7.png',
      menu_id: 2
    }, {
      id: 8,
      title: '石锅拌饭',
      price: 22,
      active: false,
      num: 1,
      image: 'image/8.jpg',
      menu_id: 2
    }, {
      id: 9,
      title: '嫩豆腐汤',
      price: 16,
      active: false,
      num: 1,
      image: 'image/9.jpg',
      menu_id: 2
    }, {
      id: 10,
      title: '刺身',
      price: 38,
      active: false,
      num: 1,
      image: 'image/10.jpg',
      menu_id: 3
    }, {
      id: 11,
      title: '照烧鸡排饭',
      price: 28,
      active: false,
      num: 1,
      image: 'image/11.jpg',
      menu_id: 3
    }, {
      id: 12,
      title: '碳烤虾尾',
      price: 39,
      active: false,
      num: 1,
      image: 'image/12.jpg',
      menu_id: 3
    }, {
      id: 13,
      title: '五花肉',
      price: 26,
      active: false,
      num: 1,
      image: 'image/13.jpg',
      menu_id: 4
    }, {
      id: 14,
      title: '羊排',
      price: 88,
      active: false,
      num: 1,
      image: 'image/14.jpg',
      menu_id: 4
    }, {
      id: 15,
      title: '金针菇',
      price: 16,
      active: false,
      num: 1,
      image: 'image/15.jpg',
      menu_id: 4
    }],
    carts: []
  },
  // 详细信息
  detail(e) {
    // 跳转详细页
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/catalog/detatil/detatil?id=' + id,
    })
  },
  // 下拉刷新
  onPullDownRefresh: function () {
    setTimeout(() => {
      wx.showToast({
        title: '成功加载数据',
        icon: 'success',
        duration: 500
      });
      wx.stopPullDownRefresh()
    }, 500);
  },
  // 展示
  onShow: function () {
    let that = this;
    // 从storage中获取选择的店铺
    let barimg=that.data.barimg;
    let selectshop = wx.getStorageSync('selectshop')[0]
    // 选择店铺
    if (!selectshop) {
      wx.showModal({
        title: '提示',
        content: '选择店铺',
        success: function (res) {
          wx.navigateTo({
            url: '/pages/index/map/map',
          })
        }
      })
    }
    // util.request(api.Mennuslistdata).then(res => {
      util.request(api.MenuList).then(res => {
      console.log(res.data)
      let menuslist = res.data.menuslist;
      menuslist=menuslist.map((item,index)=>{
        item['img']=barimg[index]
        return item
      })
      let datagoodsliat = res.data.datagoodsliat;
      that.setData({
        menus: menuslist,
        items: datagoodsliat,
        shop: selectshop
      });
      let item = [];
      let i = 0;
      for (i = 0; i < that.data.items.length; i++) {
        item.push(that.data.items[i]);
        console.log(item)
      }
      that.setData({ item, id: '' });
    });
    that.onLoad()
  },
  // tabmwnu
  tabMenu: function (event) {
    let id = event.target.dataset.classifyid;
    console.log('event:',event)
    console.log('111:',event.target.dataset.bid)
    var item = [];
    var i = 0;
    for (i = 0; i < this.data.items.length; i++) {
      if (Number(id) == this.data.items[i].classifyid) {
        item.push(this.data.items[i]);
      }
    }
    this.setData({
      id, item
    });
  },

  // 点击去购物车结账
  card: function () {
    let that = this;
    // 判断是否有选中商品
    if (that.data.orderCount.num !== 0) {
      // 跳转到购物车订单也
      wx.redirectTo({
        url: '../order/order'
      });
    } else {
      wx.showToast({
        title: '您未选中任何商品',
        icon: 'none',
        duration: 2000
      })
    }
  },

  // 选择商品属性
  selectitemkey(e) {
    console.log('e',e)

    let dataset = e.currentTarget.dataset;
    let photo = dataset.image;
    let name = dataset.name;
    let price = dataset.price;
    dataset['nums']=1
    wx.setStorageSync('dataset', dataset)
    this.setData({
      photo,
      name,
      price,
      isdosing: true
    })
  },


  // 添加购物车
  addOrder: function (event) {
    let that = this;
    let subOrders = wx.getStorageSync('subOrders') || []; // 购物单列表存储数据
    let dataset = wx.getStorageSync('dataset');
    let allselect = wx.getStorageSync('allselect');
    console.log(allselect[0][0]['name'])
    dataset['cup'] = allselect[0][0]['name']
    dataset['ico'] = allselect[1][0]['name']
    dataset['sugar'] = allselect[2][0]['name']
    dataset['dosing'] = allselect[3][0]['name']

    console.log('dataset:', dataset)
    // let index = event.target.dataset.id;
    let index = subOrders.findIndex(v => v.id === dataset.id);
    if (index === -1) {
      dataset.nums = 1;
      subOrders.push(dataset);
    } else {
      subOrders[index].nums++;
    }

    // 判断底部提交菜单显示隐藏
    if (subOrders.length == 0) {
      this.setData({
        bottomFlag: false
      });
    } else {
      this.setData({
        bottomFlag: true
      });
    }
    let num = 0;
    let money = 0;
    subOrders.forEach(item => {
      money += item.price * item.nums; // 总价格求和
      num += item.nums;
      // console.log('item.nums:',item.nums)
    });
    console.log(subOrders)
    //  想后台提交数据
    // util.request(api.CartAdd, {
      util.request(api.AddWxCarts, {
      openid:wx.getStorageSync('openid'),
      token: wx.getStorageSync('token'),
      subOrders: dataset
    }, "PUT").then(res => {
      console.log(res)
      util.request(api.ListWxCarts,{openid:wx.getStorageSync('openid')},"POST").then(res => {
        console.log('res:', res)
        let subOrders = res.data.subOrders;
        let ordercount = res.data.ordercount;
        wx.setStorageSync('subOrders', subOrders)
        // 获取缓存数据
        that.setData({
          carts: subOrders,
          orderCount: ordercount
        })
        
      })
      wx.showToast({
        title: '加入成功',
        icon: "success",
        mask: true,
      });
    });
    // util.request(api.ListWxCarts,{openid:wx.getStorageSync('openid')},"POST").then(res => {
    //   console.log('res:', res)
    //   let subOrders = res.data.subOrders;
    //   let ordercount = res.data.ordercount;
    //   wx.setStorageSync('subOrders', subOrders)
    //   // 获取缓存数据
    //   that.setData({
    //     carts: subOrders,
    //     orderCount: ordercount
    //   })
    // })
    // wx.showToast({
    //   title: '加入成功',
    //   icon: "success",
    //   mask: true,
    // });
    // 获取数据，从后台

    // 从后端获取数据


  },


  
  //加载数据 
  onLoad: function () {
    console.log(11111111111111)
    let that = this;
    // 从后端获取数据
    util.request(api.ListWxCarts,{openid:wx.getStorageSync('openid')},"POST").then(res => {
      console.log('res:',res)
      let subOrders = res.data.subOrders;
      let ordercount = res.data.ordercount;
      wx.setStorageSync('subOrders', subOrders)
      // 获取缓存数据
      that.setData({
        carts: subOrders,
        orderCount: ordercount
      })
    })
    //定义角标数字
    // this.setData({
    //   corner_data:3
    // })
    // // 获取购物车控件适配参数
    // var that =this;
    // wx.getSystemInfo({
    //   success: function (res) {
    //     console.log(res);
    //     // 屏幕宽度、高度
    //     console.log('height=' + res.windowHeight);
    //     console.log('width=' + res.windowWidth);
    //     // 高度,宽度 单位为px
    //     that.setData({
    //       windowHeight:  res.windowHeight,
    //       windowWidth:  res.windowWidth,
    //       buttonTop:res.windowHeight*0.70,//这里定义按钮的初始位置
    //       buttonLeft:res.windowWidth*0.85,//这里定义按钮的初始位置
    //     })
    //   }
    // })
  },

  touchcat(e) {
    let nums = this.data.carts.length
    if (nums != 0) {
      this.setData({
        tabIndex: 1,
        show: true,
        bottomFlag: true
      });

    } else {
      this.setData({
        tabIndex: 0,
        show: false,
        bottomFlag: false
      });
    }
  },
  // 弹出层
  showPopup() {
    this.setData({ show: true });
  },

  onClose() {
    this.setData({ show: false });
  },
  // 加
  add(e) {
    let id = e.currentTarget.dataset.id;
    let that = this;
    let items = that.data.carts
    console.log('item:add:', items)
    let index = items.findIndex(v => v.id === e.currentTarget.dataset.id);
    console.log('index:', index)
    wx.setStorageSync('subOrders', items)
    util.request(api.JiaoneCarts, {
      id: id
    }, "POST").then(res => {
      
      if(res.success){
        wx.showToast({
          title: res.msg,
          icon:'success',
          success:res=>{
            // 价格
            let num = 0;
            let money = 0.00;
            if (index === -1) {
              e.currentTarget.dataset.number = 1;
              items.push(e.currentTarget.dataset);
            } else {
              items[index].number++;
            }
            items.forEach(item => {
              money += item.good_price * item.number; // 总价格求和
              num += item.number;
              console.log(item.number);
            });
            let orderCount = {
              num,
              money
            }
            console.log('orderCount:', orderCount)

            that.setData({
              carts: items,
              orderCount: orderCount
            })
            setTimeout(() => {}, 1000);
          }
        })
    }else{
      wx.showToast({
        title: res.msg,
      })
    }
    }).catch(res=>{
      wx.showToast({
        title: res.msg,
      })
    })

    
    

  },
  // 减
  sub(e) {
    let that = this;
    let id = e.currentTarget.dataset.id
    let items = that.data.carts
    let index = items.findIndex(v => v.id === e.currentTarget.dataset.id);

    // 价格
    let num = 0
    let money = 0.00;
    if (index === -1) {
      e.currentTarget.dataset.nums = 1;
      items.push(e.currentTarget.dataset);
    } else {
      if (items[index].number > 1) {
        console.log('--')
        items[index].number--;
      } else {
        items.splice(index, 1)
        if (items.length == 0) {
          that.onClose()
        }

      }
    }
    items.forEach(item => {
      money += item.good_price * item.number; // 总价格求和
      num += item.number;
    });
    let orderCount = {
      num,
      money
    }
    that.setData({
      carts: items,
      orderCount: orderCount
    })
    //  ordercount
    console.log('orderCount:', orderCount)
    wx.setStorageSync('subOrders', items)

    util.request(api.SuboneCarts, {
      id: id
    }, "POST").then(res => {
      console.log('res', res)
    })


  },
  // 去支付
  topay(e) {
    let shopeat = this.data.shopeat;
    let outeat = this.data.outeat;
    if(shopeat==1){
      wx.removeStorageSync('outeat')
      wx.setStorageSync('shopeat', shopeat)
    }else{
      wx.removeStorageSync('shopeat')
      wx.setStorageSync('outeat', outeat)
    }

    wx.navigateTo({
      url: '/pages/catalog/order/order',
    })
  },
  // 选择取餐方式
  // 自取
  shopeat() {
    this.setData({
      shopeat: 1,
      outeat: 0
    })
    console.log(this.data.shopeat)
    console.log(this.data.outeat)
  },
  // 外卖
  outeat() {
    this.setData({
      shopeat: 0,
      outeat: 1
    })
  },
  // 选择商店
  toselectshop() {
    wx.navigateTo({
      url: '/pages/index/map/map',
    })
  },
  // 关闭属性弹窗
  toClose() {
    this.setData({
      isdosing: false
    })
  },
  // 选杯型
  selectcup(e) {
    console.log(e)
    let cupstyle = e.target.dataset.name;
    console.log(cupstyle)
    let cups = this.data.cups;
    let movecups = cups.map(item => {
      if (item.stuate == false) {
        // 第一次选择
        if (item.name == cupstyle) {
          item.stuate = true
        }

      } else {
        // 第二次选择
        if (item.name == cupstyle) {
          item.stuate = true
        } else {
          item.stuate = false
        }
      }
      return item
    })
    console.log(movecups)

    this.setData({
      cups: movecups
    })
  },
  // 选冰度
  selectico(e) {
    console.log(e)
    let icostyle = e.target.dataset.name;
    console.log(icostyle)
    let ico = this.data.ico;
    let moveico = ico.map(item => {
      if (item.stuate == false) {
        // 第一次选择
        if (item.name == icostyle) {
          item.stuate = true
        }

      } else {
        // 第二次选择
        if (item.name == icostyle) {
          item.stuate = true
        } else {
          item.stuate = false
        }
      }
      return item
    })
    console.log(moveico)
    this.setData({
      ico: moveico
    })
  },
  // 糖度
  selectsugar(e) {
    console.log(e)
    let sugarstyle = e.target.dataset.name;
    console.log(sugarstyle)
    let sugar = this.data.sugar;
    let movesugar = sugar.map(item => {
      if (item.stuate == false) {
        // 第一次选择
        if (item.name == sugarstyle) {
          item.stuate = true
        }

      } else {
        // 第二次选择
        if (item.name == sugarstyle) {
          item.stuate = true
        } else {
          item.stuate = false
        }
      }
      return item
    })
    console.log(movesugar)
    this.setData({
      sugar: movesugar
    })
  },
  // 配料
  selectdosing(e) {
    console.log(e)
    let dosingstyle = e.target.dataset.name;
    console.log(dosingstyle)
    let dosing = this.data.dosing;
    let movedosing = dosing.map(item => {
      if (item.stuate == false) {
        // 第一次选择
        if (item.name == dosingstyle) {
          item.stuate = true
        }

      } else {
        // 第二次选择
        if (item.name == dosingstyle) {
          item.stuate = true
        } else {
          item.stuate = false
        }
      }
      return item
    })
    console.log(movedosing)
    this.setData({
      dosing: movedosing
    })
  },
  // 选好了
  selectfinish() {
   let user=wx.getStorageSync('hasLogin')
    if(user){
      let allselect = [];
      let dataset = wx.getStorageSync('dataset');
      console.log('dataset:', dataset)
      let cups = this.data.cups;
      let setcups = cups.map(item => {
        if (item.stuate == true) {
          return item
        }
      })
      setcups = setcups.filter(item => item)
      console.log('setcups:', setcups)
      allselect.push(setcups);
      // attrribute
      let ico = this.data.ico;
      let setico = ico.map(item => {
        if (item.stuate == true) {
          return item
        }
      })
      setico = setico.filter(item => item)
      allselect.push(setico);
      let sugar = this.data.sugar;
      let setsugar = sugar.map(item => {
        if (item.stuate == true) {
          return item
        }
      })
      setsugar = setsugar.filter(item => item)
      allselect.push(setsugar)
      let dosing = this.data.dosing;
      let setdosing = dosing.map(item => {
        if (item.stuate == true) {
          return item
        }
      })
      setdosing = setdosing.filter(item => item)
      allselect.push(setdosing)
      console.log('allselect:', allselect)
      wx.setStorageSync('allselect', allselect)
      this.toClose();
      this.addOrder()
    }
    else{
      wx.showToast({
        title: '提示',
        content:'登陆之后才能加入购物车哟？',
        complete:res=>{
          wx.navigateTo({
            url: '/pages/me/login/login',
          })
        }
      })
    }
  }
})